package eip.chapter3.pubsub.mule;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mule.config.i18n.Message;
import org.mule.transformers.AbstractTransformer;
import org.mule.umo.transformer.TransformerException;

import eip.chapter3.pubsub.RegulationUpdate;

/**
 * We receive a String, and we transform that String to
 * a list of regulations.
 * 
 * @author nl24167
 */
public class XMLToRegulationList extends AbstractTransformer {

	private static final long serialVersionUID = 8706464583016676056L;

	private final static String ID = "id";
	private final static String NAME = "name";
	private final static String DESCRIPTION = "description";
	
	/**
	 * Do the transformation 
	 */
	@Override
	protected Object doTransform(Object XMLMessage, String encoding)
			throws TransformerException {
		String regulationString = (String)XMLMessage;		
		try {
			return getRegulationList(regulationString);
		} catch (DocumentException e) {
			Message msg = Message.createStaticMessage("Error transforming XML to List");
			throw new TransformerException(msg,e);
		}
	}
	
	/**
	 * Transform the regulations from a string to a list of regulations.
	 * 
	 * @param message the xml message to transform
	 * @return the result of the xml messages
	 * @throws DocumentException if an error occurs.
	 */
	@SuppressWarnings("unchecked")
	private List<RegulationUpdate> getRegulationList(String message) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new StringReader(message));
		List elements = document.getRootElement().elements();
		ArrayList regulationList = new ArrayList<RegulationUpdate>();
		for (int i = 0 ; i < elements.size() ; i++) {
			Element regulationElement = (Element) elements.get(i);
			int id = Integer.parseInt(regulationElement.attribute(ID).getText());
			String name = regulationElement.elementText(NAME);
			String description = regulationElement.elementText(DESCRIPTION);
			
			regulationList.add(new RegulationUpdate(id,name,description));
		}
		return regulationList;
	}

}
